import cookielib, urllib, urllib2, json

# Created by Jason Dixon 14/03/14
# http://internetimagery.com

#Connect to server and login

#Register = sign up with an account
#login = login to site
#logout = log out of site
#status = check if logged in or not
class Connect(object):
	def __init__(self):
		self.site = 'http://internetimagery.com/users/api'
		#self.site  = 'http://localhost/public_html/users/api'
		self.signin = '/access/login'
		self.signout= '/access/logout'
		self.signup = '/access/register'
		self.status = False #login status

		self.cookie = cookielib.CookieJar()
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))

 	def register(self, name, email, pass1, pass2): #register a new user
		 post_data = {}
		 post_data['user_name'] = name
		 post_data['user_email'] = email
		 post_data['user_password_new'] = pass1
		 post_data['user_password_repeat'] = pass2
		 message, result = self.send(self.signup, post_data)
		 self.status = True if result else False
		 return message, result

	def login(self, name, password): #login an existing user
		if name and password:
			post_data = {}
			post_data['user_name'] = name #username or email
			post_data['user_password'] = password
			message, result = self.send(self.signin, post_data)
			self.status = True if result else False
			return message, result
		return 'Name and Password not provided', False

	def logout(self): #logout of website
		message, result = self.send(self.signout,{})
		if result:
			self.status = False
			return message, True
		else:
			return message, False

	def send(self, web_url, post = {}):
		message, result = self._web_talk(web_url, post)
		if result:
			try:
				new_message = json.loads(message)
				if not new_message['error']:
					return new_message, True
				else:
					return new_message['error'], False
			except ValueError:
				return message, False
		return message, False

	def _web_talk(self, page, post_request = {}): #talk to website
		try:
			req = urllib2.Request(self.site+page)
			response = self.opener.open(req,urllib.urlencode(post_request),timeout=20)
			cookie = response.headers.get('Set-Cookie')
			return response.read(), True
		except urllib2.HTTPError, e:
			return e.code, False
		except urllib2.URLError, e:
			return e.args, False
		return 'Connection Failed.', False

	def __del__(self):
		print 'Connection Closed.'

